<template>
	<div class="right-table">
		<div ref="rightTableHeader" class="right-tab-header" @scroll="onRightTableHeaderScroll">
			<div v-for="(item, index) in yearMonthList" :key="item.key" :style="{height: `${cellHeight}px`}">
				<div v-if="item.type === 2" class="right-tab-header-d-container">
					<!--年-月-->
					<div :style="setYearMonthCellStyle(item, index, yearMonthList.length)" class="right-tab-header-y-m-item">{{ item.yearMonth }}</div>
					<!--日-->
					<div v-if="tableHeaderSwitchType === 'date'" class="right-tab-header-date-week-box">
						<div
							v-for="(dateItem, dateIndex) in item.dateList"
							:key="dateIndex"
							class="header-date-item"
							:style="setDateCellStyle(item, dateItem, index, yearMonthList.length, dateIndex, item.dateList.length)"
						>{{ dateItem.day }}</div>
					</div>
					<!--周-->
					<div v-else class="right-tab-header-date-week-box">
						<div
							v-for="(weekItem, weekIndex) in item.weekList"
							:key="weekItem.weekNum"
							class="header-date-item"
							:style="setWeekCellStyle(weekItem, index, yearMonthList.length, weekIndex, item.weekList.length)"
						>
							<el-popover
								placement="top-start"
								trigger="hover"
							>
								<div style="display: flex;flex-direction: column;align-items: center;">
									<span>{{ item.yearMonth }}</span>
									<span>{{ `${weekItem.dayList[0].day} ~ ${weekItem.dayList[weekItem.dayList.length - 1].day}号` }}</span>
								</div>
								<span slot="reference">{{ ` ${weekItem.dayList[0].day} ~ ${weekItem.dayList[weekItem.dayList.length - 1].day}号` }}</span>
							</el-popover>
						</div>
					</div>
				</div>
			</div>
			<div class="cell-gutter" :style="{height: `${cellHeight}px`}"></div>
		</div>
		<div ref="rightTableBody" :style="{height: `${height - cellHeight - 4}px`}" class="right-tab-body" @scroll="onRightTableBodyScroll">
			<div v-if="tableData.length">
				<div
					v-for="(item, index) in tableData"
					:key="item.id"
					class="right-tab-body-item"
					:style="{height: `${cellHeight}px`}"
				>
					<div
						:class="index === hoverIdx ? 'column-bar hover-style' : 'column-bar'"
						:style="setColumnBarStyle(item)"
						@mouseover="onMouseOver(index)"
						@mouseleave="onMouseLeave(index)"
					>
						<div
							v-for="(taskItem, taskIndex) in item.taskList"
							:key="taskIndex"
							class="progress-bar"
							:style="setProgressBarStyle(taskItem)"
							style="position: relative;"
						>
							<!--<el-popover placement="top-start" :title="item.yearMonth" trigger="hover">
								<popoverList :item="taskItem"></popoverList>
								<div slot="reference" style="position: absolute;left: 0;top:0;height: 100%;display: flex;align-items: center;">
									<span class="el-icon-s-opportunity flag"></span>
								</div>
							</el-popover>-->
							<div style="position: absolute;left: 0;top:0;height: 100%;display: flex;align-items: center;">
								<span class="el-icon-s-opportunity flag"></span>
							</div>
							<div :style="setProgressRatioStyle(taskItem)" class="progress-ratio">
								<span class="progress-ratio-val">{{ `${ taskItem[progressBarTextKey1] ? taskItem[progressBarTextKey1] : '' }` }} ( {{ `${ taskItem[progressBarTextKey2] ? taskItem[progressBarTextKey2] : '' }` }} )</span>
								<!--<div class="progress-msg">{{ `${ taskItem[progressBarTextKey2] ? taskItem[progressBarTextKey2] : '' }` }}</div>-->
							</div>
						</div>
					</div>
				</div>
			</div>
			<div v-else class="right-tab-body-item">
				<div :style="setNoData(tableDateHeader.tableHeaderAllDays)">
					<div class="progress-bar no-data">暂无数据</div>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
    import leftRightMix from './left-right-mix';
    import { debounce, formatDate, formatMonth } from '../../../../utils/jk/jk-tool';
    import popoverList from './popover-list';
    export default {
        mixins: [leftRightMix],
        components: { popoverList },
        props: {
            checkArr: {
                type: Array,
                default() {
                    return [];
                }
            },
            tableHeaderSwitchType: {
                type: String,
                default: 'date'
            },
            tableData: {
                type: Array,
                default() {
                    return [];
                }
            },
            startDateKeyName: {
                type: String,
                default: 'startDate'
            },
            tableDateHeader: {
                type: Object,
                default() {
                    return {};
                }
            },
            scrollTop: {
                type: Number,
                default: 0
            },
            scrollLeft: {
                type: Number,
                default: 0
            },
            height: {
                type: Number,
                default: 0
            },
            progressBarTextKey1: {
                type: String,
                default: 'code'
            },
            progressBarTextKey2: {
                type: String,
                default: 'productName'
            },
            hoverIndex: {
                type: Number,
                default: null
            }
        },
        data() {
            return {
                hoverIdx: null,
                headerList: [],
                yearMonthList: []
            };
        },
        methods: {
            setNoData(tableHeaderAllDays) {
                return {
                    width: `${tableHeaderAllDays * this.dateCellWidth}px`,
                    display: 'flex',
                    alignItems: 'center',
                    flexShrink: '0'
                };
            },
            getDay(e) {
                const day = new Date(e).getDate();
                return day;
            },
            getDateGroup(startDate, endDate) {
                const days = (Date.parse(endDate) - Date.parse(startDate)) / (24 * 60 * 60 * 1000);
                this.allDateList = [];
                // 获取所有天数
                for (let i = 0; i <= days; i++) {
                    this.allDateList.push({
                        sortNum: i + 1,
                        date: formatDate(Date.parse(startDate) + (i * 24 * 60 * 60 * 1000)),
                        yearMonth: formatMonth(Date.parse(startDate) + (i * 24 * 60 * 60 * 1000)),
                        day: this.getDay(Date.parse(startDate) + (i * 24 * 60 * 60 * 1000))
                    });
                }
                // 安装月份分组
                const aid = {};
                const arr = [];
                this.allDateList.forEach(x => {
                    if (!aid[x.yearMonth]) {
                        aid[x.yearMonth] = 1;
                        arr.push({
                            type: 2,
                            yearMonth: x.yearMonth,
                            dateList: [x]
                        });
                    } else {
                        arr.forEach(k => {
                            if (k.yearMonth === x.yearMonth) k.dateList.push(x);
                        });
                    }
                });
                this.yearMonthList = arr.map(mItem => {
                    mItem.weekList = [];
                    let weekNum = 1; // 第几周
                    let weekItem = { weekNum: 0, dayList: [] };
                    let weekStart = new Date(mItem.dateList[0].date).getDay(); // 星期几
                    mItem.dateList.forEach((dItem, dIndex) => {
                        if (weekStart === 7 || dIndex === mItem.dateList.length - 1) {
                            weekStart = 1;
                            weekItem.weekNum = weekNum;
                            weekItem.dayList.push(dItem);
                            mItem.weekList.push(weekItem);
                            weekItem = { weekNum: 0, dayList: [] };
                            weekNum++;
                        } else {
                            weekItem.weekNum = weekNum;
                            weekItem.dayList.push(dItem);
                            weekStart++;
                        }
                    });
                    return mItem;
                });
                this.headerList = [...this.yearMonthList];
            },
            setWeekCellStyle(item, index, len, weekIndex, weekLen) {
                let isToDay = false;
                item.dayList.forEach(x => {
                    if (this.tableDateHeader.toDay === x.date) isToDay = true;
                });
                let styleItem = {};
                styleItem = {
                    width: `${this.dateCellWidth * item.dayList.length}px`,
                    height: `${this.cellHeight / 2}px`,
                    background: isToDay ? '#19be6b' : '',
                    color: isToDay ? '#fff' : ''
                };
                if (index + 1 === len && weekIndex + 1 === weekLen) {
                    styleItem.borderRight = 'none';
                }
                return styleItem;
            },
            setYearMonthCellStyle(item, index, len) {
                let styleItem = {};
                styleItem = {
                    width: `${this.dateCellWidth * item.dateList.length}px`,
                    height: `${this.cellHeight / 2}px`
                };
                if (index + 1 === len) {
                    styleItem.borderRight = 'none';
                }
                return styleItem;
            },
            setDateCellStyle(item, dateItem, index, len, dateIndex, dateLen) {
                let styleItem = {};
                styleItem = {
                    width: `${this.dateCellWidth}px`,
                    height: `${this.cellHeight / 2}px`,
                    background: this.tableDateHeader.toDay === dateItem.date ? '#19be6b' : '',
                    color: this.tableDateHeader.toDay === dateItem.date ? '#fff' : ''
                };
                if (index + 1 === len && dateIndex + 1 === dateLen) {
                    styleItem.borderRight = 'none';
                }
                return styleItem;
            },
            setProgressBarStyle(item) {
                let leftNum = 0;
                let leftPx = '';
                let obj = {};
                if (item.days > 0) {
                    if (item.isBefore) {
                        this.allDateList.forEach(x => {
                            if (x.date === item[this.startDateKeyName]) leftNum = x.sortNum;
                        });
                        leftPx = `${(leftNum - 1) * this.dateCellWidth}px`;
                    } else {
                        leftNum = 0;
                        leftPx = '0px';
                    }
                    obj = {
                        width: `${(item.days * this.dateCellWidth)}px`,
                        overflow: 'hidden',
                        height: `${this.cellHeight * 0.6}px`,
                        left: leftPx
                    };
                } else {
                    obj = {
                        display: 'none'
                    };
                }
                return obj;
            },
            setProgressRatioStyle(item) {
                if (item.days > 0) {
                    let wid = 0;
                    if (item.ratio > 0) {
                        wid = item.ratio > 1 ? `${(item.days * this.dateCellWidth)}px` : `${item.days * this.dateCellWidth * item.ratio}px`;
                    } else {
                        wid = '0px';
                    }
                    return {
                        width: wid,
                        height: `100%`,
                        lineHeight: `${this.cellHeight * 0.6}px`,
                        background: '#2d8cf0',
                        color: '#fff'
                    };
                }
            },
            onCheckRow({ id }) {
                this.$emit('on-check', id);
            },
            onMouseLeave() {
                this.hoverIdx = null;
                this.$emit('on-mouse', this.hoverIdx);
            },
            onMouseOver(index) {
                this.hoverIdx = index;
                this.$emit('on-mouse', this.hoverIdx);
            },
            onRightTableBodyScroll() {
                // debounce(() => {
                this.$refs.rightTableHeader.scrollLeft = this.$refs.rightTableBody.scrollLeft;

                if (this.$refs.leftTableFixed) {
                    this.$refs.leftTableFixed.scrollTop = this.$refs.rightTableBody.scrollTop;
                }
                this.$emit('on-scroll', {
                    scrollTop: this.$refs.rightTableBody.scrollTop
                });
                // }, 10);
            },
            onRightTableHeaderScroll() {
                // debounce(() => {
                this.$refs.rightTableBody.scrollLeft = this.$refs.rightTableHeader.scrollLeft;

                /* this.$emit('on-scroll', {
                    scrollTop: this.$refs.rightTableHeader.scrollTop
                });*/
                // }, 10);
            },
            setColumnBarStyle(item) {
                return {
                    width: `${item.tableHeaderAllDays * this.dateCellWidth}px`,
                    display: 'flex',
                    alignItems: 'center',
                    background: this.setCheckStyle(item)
                };
            }
        },
        watch: {
            tableHeaderSwitchType(newVal) {
                if (newVal === 'week') {
                    this.dateCellWidth = 17;
                } else {
                    this.dateCellWidth = 40;
                }
            },
            scrollTop(newVal) {
                this.$refs.rightTableHeader.scrollTop = newVal;
                this.$refs.rightTableBody.scrollTop = newVal;
            },
            tableDateHeader: {
                handler(newVal) {
                    this.getDateGroup(newVal.startDate, newVal.endDate);
                },
                deep: true
            },
            hoverIndex(newVal) {
                this.hoverIdx = newVal;
            }
        }
    };
</script>
<style scoped lang="scss">
    @import "./left-right-table";
</style>
